# -*- coding: utf-8 -*-
# @Time    : 2025/1/7 16:14
# @Author  : 就来杯柠檬水
# @File    : 11.py
# @Software: PyCharm


def binary_search(arr, target):
    left, right = 0, len(arr) - 1

    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid  # 找到了目标元素
        elif arr[mid] < target:
            left = mid + 1  # 在右半部分查找
        else:
            right = mid - 1  # 在左半部分查找

    return -1  # 未找到目标元素

# 示例用法
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target = 5
result = binary_search(arr, target)

if result != -1:
    print(f"目标元素 {target} 的索引是: {result}")
else:
    print("目标元素未找到")
